package com.open.data.component

import android.content.Context
import androidx.lifecycle.LiveData
import com.open.data.component.dao.WordDao
import com.open.data.component.data.Word
import com.open.data.component.database.WordRoomDatabase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch


/**************************************************************
 *
 *
 *
 *
 * @author :guangjing.feng.o
 * @createTime: 2021/6/3.
 * @modifyTime:
 * @modifyAuthor:
 * @description:
 *
 ************************************************************/
class Repository(context: Context) {
    private val wordsLive: LiveData<List<Word?>?>?

    fun getWordsLive(): LiveData<List<Word?>?>? {
        return wordsLive
    }

    //用来调用数据库操作
    private var wordDao: WordDao?

    fun insert(vararg words: Word?) {
        GlobalScope.launch (Dispatchers.IO){
            wordDao?.insertWord(*words)
        }
    }

    fun delete(vararg words: Word?) {
        GlobalScope.launch (Dispatchers.IO){
            wordDao?.delete(*words)
        }
    }

    fun update(vararg words: Word?) {
        GlobalScope.launch (Dispatchers.IO){
            wordDao?.delete(*words)
        }
    }

    fun deleteAll() {
        GlobalScope.launch (Dispatchers.IO){
            wordDao?.deleteAll()
        }
    }

    init {
        val wordRoomDatabase =
            WordRoomDatabase.getInstance(context.getApplicationContext())
        wordDao = wordRoomDatabase!!.getWordDao()
        wordsLive = wordDao!!.getAll()
    }
}